import Vue from 'vue';
const RESPONSE_TYPE_SUCCESS = '10000';

let requestCount = 0;

export default async function({
	baseUrl = Vue.prototype.$fmBaseURL,
	...config // 包含所有的 data、header、method... 具体查看uni-app官网
} = {
	baseUrl: Vue.prototype.$fmBaseURL,
}, {
	shouldReLaunchToRegiterPage = true,
	shouldLoadingShow = true,
	shouldErrorToastShow = true,
	isRaw = false,
} = {
	shouldReLaunchToRegiterPage: true,
	shouldLoadingShow: true,
	shouldErrorToastShow: true,
	isRaw: false,
}) {
	// url 必填，所以根据环境和默认值，加上baseUrl后重新设置
	config.url = `${baseUrl}${config.url}`;
	if (!config.header || !config.header['content-type']) {
		config.header = {
			...config.header,
			'content-type': 'application/x-www-form-urlencoded'
		};
	}
	if (!config.method) {
		config.method = 'POST';
	}

	requestCount += 1;
	if (shouldLoadingShow) {
		uni.showLoading({
			title: '请稍候...',
			mask: true
		});
	}
	let response;
	try {
		response = await uni.request(config);
	} catch (e) {
		throw e;
	} finally {
		requestCount -= 1;
		if (shouldLoadingShow && requestCount <= 0) {
			uni.hideLoading();
		}
	}

	const [error, {
		statusCode,
		data: rawData
	}] = response;
	
	if (error) {
		throw error;
	}
	if (shouldReLaunchToRegiterPage && statusCode === 401) {
		uni.reLaunch({
			url: '/modules/register/pages/index/index'
		});
		if (isRaw) {
			return {
				success: false,
				data: ''
			};
		} else {
			return '';
		}
	}

	const data = JSON.parse(
		JSON.stringify(rawData)
		.replace(/:null/g, ':""')
		.replace(/:"null"/, ':""')
	);

	const success = data.code === RESPONSE_TYPE_SUCCESS;
	if (shouldErrorToastShow && !success) {
		uni.showToast({
			title: data.msg || '请求失败，请联系管理员',
			icon: 'none'
		});
	}

	if (isRaw) {
		return {
			...data,
			success
		};
	} else {
		return data.data;
	}
}
